// pages/order-detail/order-detail.js
const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopCartItemDiscounts:[],
    totalPriceInt:100,
    totalPriceDecimal:0,
    totalNum:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel()
    let newThis = this //引入this对象
    eventChannel.on("dataPoster",function(data){ //监听dataPoster事件
      newThis.setData({
        shopCartItemDiscounts : data
      })
      let itemList = newThis.data.shopCartItemDiscounts 
      newThis.countPrice(itemList)
      newThis.countProductNum(itemList)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let itemList = this.data.shopCartItemDiscounts
    this.countPrice(itemList)
    this.countProductNum(itemList)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  /*
    计算总价函数
  */
  countPrice(data) {
    let totalPrice = 0
    let itemList = data
    for(let a = 0;a<itemList.length;a++){
      totalPrice+= itemList[a].shopCartItems[0].price * itemList[a].shopCartItems[0].prodCount
      totalPrice = parseFloat(totalPrice.toFixed(2))
    }
    this.setData({
      totalPriceInt:totalPrice
    })
  },
  countProductNum(data){
    let totalNum = 0
    let itemList = data
    for(let a = 0;a<itemList.length;a++){
      totalNum+= itemList[a].shopCartItems[0].prodCount
    }
    this.setData({
      totalNum:totalNum
    })
  },

  uploadList(){
    for(let a=0;a<this.data.shopCartItemDiscounts.length;a++){ //给商品计算总价
      let randString = getApp().getRandomString(10)
      this.data.shopCartItemDiscounts[a].shopCartItems[0].listID = randString

      let b = this.data.shopCartItemDiscounts[a].shopCartItems[0].price * this.data.shopCartItemDiscounts[a].shopCartItems[0].prodCount
      this.data.shopCartItemDiscounts[a].shopCartItems[0].oriPrice = parseFloat(b.toFixed(2))
    }
    wx.request({
      url: getApp().globalData.serverURL+"/saveOrderList",
      data:[this.data.shopCartItemDiscounts,wx.getStorageSync('token')],
      dataType:"json",
      method:"POST",
      success:function(res) {
        wx.showToast({
          title: '成功'
        })
        setTimeout(() => {
          wx.navigateTo({
            url: '../orderList/orderList',
          })
        }, 3000);
        getApp().globalData.isShopped = true
      }
    })
  }
})